using System.IO;

namespace Engine.FileFormats3D.C11Syndikat
{
    public class GeoFile
    {
        #region Private Fields

        private ushort[] allIndices;
        private C11VertexBlock[] vertexBlocks;

        #endregion Private Fields

        #region Public Constructors

        public GeoFile()
        {
        }

        #endregion Public Constructors

        #region Public Properties

        public ushort[] AllIndices
        {
            get { return allIndices; }
            set { allIndices = value; }
        }

        #endregion Public Properties

        #region Internal Properties

        internal C11VertexBlock[] VertexBlocks
        {
            get { return vertexBlocks; }
            set { vertexBlocks = value; }
        }

        #endregion Internal Properties

        #region Internal Methods

        internal static GeoFile FromFile(string filename, QadFile qadFile)
        {
            GeoFile geoFile = new GeoFile();
            FileStream fs = new FileStream(filename, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);

            char[] identy = br.ReadChars(4);
            short index1 = br.ReadInt16();
            short index2 = br.ReadInt16();
            short index3 = br.ReadInt16();
            short index4 = br.ReadInt16();
            short index5 = br.ReadInt16();
            short index6 = br.ReadInt16();
            short index7 = br.ReadInt16();
            short index8 = br.ReadInt16();
            short index9 = br.ReadInt16();
            short index10 = br.ReadInt16();
            short index11 = br.ReadInt16();
            short index12 = br.ReadInt16();
            short index13 = br.ReadInt16();
            short index14 = br.ReadInt16();

            int[] numberOfVerticesPerBlock = new int[64];
            for (int i = 0; i < numberOfVerticesPerBlock.Length; i++)
            {
                numberOfVerticesPerBlock[i] = br.ReadInt32();
            }

            // Read vertices.
            geoFile.VertexBlocks = new C11VertexBlock[numberOfVerticesPerBlock.Length];
            for (int i = 0; i < numberOfVerticesPerBlock.Length; i++)
            {
                int numberOfVertices = numberOfVerticesPerBlock[i];
                if (numberOfVertices > 0)
                    geoFile.VertexBlocks[i] = C11VertexBlock.FromStream(br, numberOfVertices);
                else
                    break;
                // Ends at: 89275328 (Autobahn)
            }

            //Read the indices
            geoFile.AllIndices = new ushort[qadFile.NumberOfPolygons * 3];
            for (int i = 0; i < qadFile.NumberOfPolygons * 3; i++)
            {
                geoFile.AllIndices[i] = br.ReadUInt16();
            }

            br.Close();
            fs.Close();
            return geoFile;
        }

        #endregion Internal Methods
    }
}